"""Main Combat Turtles script.

Running this script automatically loads all necessary modules to play a game
of Turtle Combat and then starts the game.
"""

import argparse
import inspect
import game
import ai

# 以下为自定义代码
import tkinter
from  tkinter  import ttk
from tkinter import *

#=============================================================================

def combat_turtles(tid1=-1, tid2=-1, aid=-1, cutoff=-1):

    print("Finding Combat Turtle AI modules...", end="")
    turtle_classes = []
    for f in ai.__all__:
        # Use static method to test whether the module includes the class
        try:
            eval("ai." + f + ".CombatTurtle.class_name()")
            turtle_classes.append("ai." + f + ".CombatTurtle")
        # If not, skip
        except AttributeError:
            pass

    # Quit if no valid modules were found
    if len(turtle_classes) == 0:
        print("\nNo valid modules were found in the ai/ directory.")
        print("Please review the documentation to see the required format.")
        print("https://github.com/adam-rumpf/turtle-combat")
        return None

    # Display results
    print(" Done!")
    print(str(len(turtle_classes)) + " module(s) found.")

    # Display AI choices
    print()
    _ai_table(turtle_classes)

    # Display arena choices
    print()
    arena_names = game.obj.arena.Arena.get_names() # list of all arena layouts
    _arena_table(arena_names)


    #------------- UI 代码-----------------------

    choice = [0,0,0]    # 存放下拉列表选择的参数.分别为 player1,player2,area
    def g1(*args):      # 每个下拉列表对应一个独立的函数
        name = comboExample1.get()
        for i in range(1, len(turtle_classes)):
            if(name == turtle_classes[i]):
                choice[0] = i
                break
        print('player1={}'.format(choice[0]))

    def g2(*args):
        name = comboExample2.get()
        for i in range(1, len(turtle_classes)):
            if(name == turtle_classes[i]):
                choice[1] = i
                break
        print('player2={}'.format(choice[1]))

    def g3(*args):
        choice[2] = comboExample3.get()
        print('playerground={}'.format(choice[2]))

    # 界面绘制
    root = Tk()
    root.title("请选择战斗双方的乌龟")
    Label(root, text="请选择红方参赛乌龟").grid(row=0, column=0)
    comboExample1 = ttk.Combobox(root,
                                values=turtle_classes,  # 下拉参数列表
                                state='readonly')       # 下拉选项不可修改
    comboExample1.grid(row=0, column=1)                 # 组件放置位置
    comboExample1.current(0)                            # 默认选项
    comboExample1.bind("<<ComboboxSelected>>",g1)       # 绑定点击事件



    Label(root, text="请选择蓝方参赛乌龟").grid(row=1, column=0)
    comboExample2 = ttk.Combobox(root,
                                values=turtle_classes,
                                state='readonly')
    comboExample2.grid(row=1, column=1)
    comboExample2.current(0)
    comboExample2.bind("<<ComboboxSelected>>",g2)

    # 读取场地代号
    arena_names = game.obj.arena.Arena.get_names()
    arena_layout=[]
    for i in range(0, len(arena_names)):
        arena_layout.append(i)
    Label(root, text="请选择场地").grid(row=2, column=0)
    comboExample3 = ttk.Combobox(root,
                                values=arena_layout,
                                state='readonly')
    # comboExample3.current(0)
    comboExample3.grid(row=2, column=1)
    comboExample3.current(0)
    comboExample3.bind("<<ComboboxSelected>>",g3)

    # 点击此按钮后，退出 UI 界面，开始战斗
    button1 = Button(root, text='选择号参赛选手和场地后，点我开始比赛', command=root.destroy)
    button1.grid(row= 3, column=0)

    root.mainloop()
    #----------------UI代码------------------------------------------

    # Show players
    print("\nPlayer 1: " + eval(turtle_classes[choice[0]] + ".class_name()"))
    print("Player 2: " + eval(turtle_classes[choice[1]] + ".class_name()"))

    # Show arena
    print("\nArena: " + arena_names[int(choice[2])])

    # Create game object with chosen turtles and arena
    print("\nOpening Combat Turtles.")
    print("Game in progress...")
    gm = game.tcgame.TurtleCombatGame(class1=turtle_classes[choice[0]],
                                      class2=turtle_classes[choice[1]],
                                      layout=int(choice[2]), cutoff=cutoff)

    # Delete game object when done
    print("Closing Combat Turtles.")
    del gm

#-----------------------------------------------------------------------------

def _ai_table(classes):
    """_ai_table(classes) -> None
    Prints a table of listed Combat Turtle classes.

    Requires the following positional arguments:
        classes (list (str)) -- list of full class name strings
    """

    # Print header
    print("Index\tName\t\tDescription")
    print("-"*60)

    # Print names and descriptions
    for i in range(len(classes)):
        name = eval(classes[i] + ".class_name()")
        desc = eval(classes[i] + ".class_desc()")
        print(str(i) + "\t" + name + "\t" + desc)

#-----------------------------------------------------------------------------

def _arena_table(arenas):
    """_arena_table(arenas) -> None
    Prints a table of listed arena layouts.

    Requires the following positional arguments:
        arenas (list (str)) -- list of arena layout names
    """

    # Print header
    print("Index\tName")
    print("-"*60)

    # Print names
    for i in range(len(arenas)):
        print(str(i) + "\t" + arenas[i])
#-----------------------------------------------------------------------------
def Game_UI(player1, payer2, playground):  # 绘制 UI 界面
    # 读取 AI 乌龟名称
    turtle_classes = []
    for f in ai.__all__:
        # Use static method to test whether the module includes the class
        try:
            eval("ai." + f + ".CombatTurtle.class_name()")
            turtle_classes.append("ai." + f + ".CombatTurtle")
        # If not, skip
        except AttributeError:
            pass

    def go(player, num):   #处理事件，*args表示可变参数
        if(num == 1):
            player = comboExample1.get()
        elif(num == 2):
            player = comboExample2.get()
        else:
            player = comboExample3.get()
        print(player) #打印选中的值

    root = Tk()
    root.title("请选择战斗双方的乌龟")
    f1 = Frame(root)
    f2 = Frame(root)
    Label(root, text="请选择红方参赛乌龟").grid(row=0, column=0)
    comboExample1 = ttk.Combobox(root,
                                values=turtle_classes)
    comboExample1.current(0)
    comboExample1.grid(row=0, column=1)
    player1 = 0
    comboExample1.bind("<<ComboboxSelected>>",go(player1, 1))
    print(player1)



    Label(root, text="请选择蓝方参赛乌龟").grid(row=1, column=0)
    comboExample2 = ttk.Combobox(root,
                                values=turtle_classes)
    comboExample2.current(0)
    comboExample2.grid(row=1, column=1)
    player2 = 0
    comboExample1.bind("<<ComboboxSelected>>",go(player2, 2))
    print(player2)

    # 读取场地代号
    arena_names = game.obj.arena.Arena.get_names()
    arena_layout=[]
    for i in range(1, len(arena_names)):
        arena_layout.append(i)
    Label(root, text="请选择场地").grid(row=2, column=0)
    comboExample3 = ttk.Combobox(root,
                                values=arena_layout)
    comboExample3.current(0)
    comboExample3.grid(row=2, column=1)
    playground = 0
    comboExample1.bind("<<ComboboxSelected>>",go(playground, 3))
    print(playground)

    flage = 0
    def isClick():
        flage = 1

    button = Button(root, text='开始比赛')
    Button(root, command=isClick())
    button.grid(row= 3, column=0)

    # if(flage == 1):
    #     k = PyKeyboard()
    #     print('模拟输入')
    #     k.type_string(player1)# –模拟键盘输入字符串
    #     k.type_string(player2)
    #     k.type_string(playground)
    root.mainloop()

#-----------------------------------------------------------------------------
#=============================================================================

# Define docstrings for command line usage
_vers = """
Combat Turtles v1.1.0
Copyright (c) 2021 Adam Rumpf <adam-rumpf.github.io>
Released under MIT License <github.com/adam-rumpf/combat-turtles>
"""
_desc = """
Initializes a game of Combat Turtles. Command line arguments can be supplied
to specify player AIs and the arena (see below for details). Excluding any of
these arguments will prompt the user to specify them on startup.

Note that the player AIs are indexed alphabetically, which may cause indices
to change as new modules are added to the ai/ directory.
"""
_epil = ("See full documentation online at " +
         "<adam-rumpf.github.io/combat-turtles>.")

# Initialize game (options can be set from command line)
if __name__ == "__main__":

    # Initialize argument parser
    parser = argparse.ArgumentParser(description=_desc, epilog=_epil,
                                     formatter_class=
                                     argparse.RawDescriptionHelpFormatter)

    # Define arguments
    parser.add_argument("-v", "--version", action="version", version=_vers)
    parser.add_argument("-f", "--first", action="store", default=-1,
                        type=int, dest="p1", help="player 1 AI index")
    parser.add_argument("-s", "--second", action="store", default=-1,
                        type=int, dest="p2", help="player 2 AI index")
    parser.add_argument("-a", "--arena", action="store", default=-1,
                        type=int, dest="a", help="arena index")
    parser.add_argument("-c", "--cutoff", action="store", default=-1,
                        type=int, dest="lim",
                        help="iteration cutoff (default: unlimited)")

    # Parse command line arguments
    args = parser.parse_args()

    # Run game
    combat_turtles(tid1=args.p1, tid2=args.p2, aid=args.a, cutoff=args.lim)
